# --*-- coding: utf-8 --*--

import configparser
from configparser import NoOptionError, NoSectionError
import os
import logging
import codecs

from src import Public
from src.exception.seleniumexecption import SeleniumTypeError

PROJECT_DIR = os.path.dirname(
	os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
)

CONFIG_PATH = os.path.join(PROJECT_DIR, "Config", "config.ini")


# log日志界别及读写操作
class GetConfig(object):
	@staticmethod
	def get_config() -> configparser.ConfigParser:
		config = configparser.ConfigParser()
		with open(
				file=CONFIG_PATH, mode="rb"
		) as f:  # 2018-6-10 BEGIN 判断文件的编码类型 如果是UTF-8 BOM格式，则将其转化为无BOM格式
			s = f.read()
		if s.startswith(codecs.BOM_UTF8):  # 带BOM的文件是以 b'\xef\xbb\xbf' 开头
			s = s[len(codecs.BOM_UTF8):]  # 截取 b'\xef\xbb\xbf' 到文件结尾
			with open(file=CONFIG_PATH, mode="wb") as f:  # 保存为无BOM格式
				f.write(s)
		coding = Public.get_file_coding(filepath=CONFIG_PATH).get("encoding")
		config.read(
			filenames=CONFIG_PATH, encoding=coding
		)  # 2018-6-10 END 判断文件的编码类型 如果是UTF-8 BOM格式，则将其转化为无BOM格式
		return config

	@property
	def project_dir(self) -> str:
		# return self.get_config().get(section="PROJECT", option="project_dir")
		# 不在需要配置项目路径，项目迁移更加灵活。
		return PROJECT_DIR

	@property
	def logging_level(self) -> int:
		section = "LOG"
		option = "logging_level"
		default = "INFO"
		try:
			level = self.get_config().get(section=section, option=option)
		except (NoOptionError, NoSectionError):
			level = default
		if str.upper(level) == "DEBUG":
			return logging.DEBUG
		elif str.upper(level) == "INFO":
			return logging.INFO
		elif str.upper(level) == "WARN" or str.upper(level) == "WARNING":
			return logging.WARNING
		elif str.upper(level) == "CRITICAL" or str.upper(level) == "FATAL":
			return logging.CRITICAL
		elif str.upper(level) == "ERROR":
			return logging.ERROR
		else:
			raise SeleniumTypeError(
				'配置文件中定义的日志级别logging_level为"%s",请填写以下几种级别“INFO、DEBUG、WARNING、ERROR、CRITICAL”'
				% level
			)

	@property
	def log_colors_config(self):
		section = "CONSOLE_LOG_COLOR"
		options = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
		log_colors_config = {}
		for option in options:
			color = self.get_config().get(section=section, option=option)
			log_colors_config[option] = color
		return log_colors_config


Config = GetConfig()
